package com.sna.snaapplication.service.LogReg.impl;

import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.entity.usercore.UserRole;
import com.sna.snaapplication.mapper.UserMapper;

import com.sna.snaapplication.service.LogReg.RegisterService;
import com.sna.snaapplication.service.UserSys.RoleService;
import com.sna.snaapplication.service.UserSys.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    UserRoleService userRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public void reg(String username, String password) {

        //加密
        String encode = bCryptPasswordEncoder.encode(password);

        // 创建用户对象并设置角色
        User user = new User();
        user.setUserName(username);
        user.setPassword(encode);

        // 设置用户创建时间
        user.setCreateTime(new Date());
        // 添加用户到数据库
        userMapper.insert(user);

        //查询到新插入的用户id
        Long userId = user.getUserId();
        /*
         * 添加用户角色
         * */

        //查询用户角色的role_id

        Long roleId = roleService.FindId("common");

        UserRole userRole = new UserRole();
        userRole.setUserId(userId).setRoleId(roleId);

        //插入用户角色user_role表中
        Integer num =userRoleService.saveUserRole(userRole);

        if(num>0){
            System.out.println("添加用户角色成功");
        }else{
            System.out.println("添加用户角色失败");
            //如果插入不成功之前插入的用户信息也要删除
            userMapper.deleteById(userId);
        }


    }


}
